<template>
<!--.prevent事件修饰符   阻止事件的默认行为 -->
   <ul class="lists">
     <li class="item"
     v-for="item of letters"
     :key="item"
     :ref="item"
     @touchstart.prevent="handleTouchStart"
     @touchmove="handleTouchMove"
     @touchend="handleTouchEnd"
     @click="LetterClick">{{item}}</li>
   </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  computed: {
    // 将字母表赋值给letters
    letters () {
      const letters = []
      for (var i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      // 根据这个记录滑动过程
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  // 生命周期钩子 当数据发生改变时,页面重新渲染时
  updated () {
    this.startY = this.$refs.A[0].offsetTop
  },
  methods: {
    // 点击字母跳转响应的内容
    LetterClick (e) {
      // 向父级组件传值,在通过父级转发给兄弟组件
      // 向父级触发事件
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    // 滚动字母表跳转由字母开头的城市
    handleTouchMove  (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        // 延迟16毫秒再去执行滑动事件
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 79
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd   () {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~stylus/varibles.styl'
  .lists
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem
    .item
      line-height: .42rem
      text-align: center
      color: $bgColor
</style>
